import React, { PureComponent, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Select, Button, Modal, message, Divider, Badge } from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './RoleManage.less';

const statusMap = { 禁用: 'error', 启用: 'success' };
const status = { 禁用: '禁用', 启用: '启用' };
const enableMap = { 禁用: 1, 启用: 0 };
const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ role, account, loading }) => ({
  role,
  account,
  loading: loading.models.account,
}))
@Form.create()
export default class AccountManage extends PureComponent {
  state = {
    modalVisible: false,
    editVisible: false,
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const {
      dispatch,
      account: { pagination },
    } = this.props;
    dispatch({
      type: 'account/fetch',
      payload: { page: pagination.current, pageSize: pagination.pageSize },
    });
    dispatch({
      type: 'role/fetchName',
    });
    dispatch({
      type: 'role/fetchType',
    });
    dispatch({
      type: 'role/fetchUserType',
    });
    dispatch({
      type: 'role/fetchUserOrg',
    });

  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'account/fetch',
      payload: params,
    });
  };

  delAccount = record => {
    Modal.confirm({
      title: '确认删除',
      content: '确认要删除帐号么？删除后不可恢复',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        const { dispatch } = this.props;
        dispatch({
          type: 'account/remove',
          payload: {
            userName: record.userName,
          },
          callback: () => {
            message.success('删除帐号成功！');
          },
        });
      },
    });
  };

  disAccount = record => {
    Modal.confirm({
      title: '变更帐号状态',
      content: record.userStatus === '禁用' ? '确认要启用帐号么？' : '确认要禁用帐号么？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        const { dispatch } = this.props;
        dispatch({
          type: 'account/disabled',
          payload: {
            userName: record.userName,
            userEnable: enableMap[record.userStatus],
          },
          callback: () => {
            record.userStatus === '禁用'
              ? message.success('禁用帐号成功！')
              : message.success('启用帐号成功！');
          },
        });
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {};
      for (const key of Object.keys(fieldsValue)) {
        if (fieldsValue[key]) {
          values[key] = fieldsValue[key];
        }
      }
      //console.log('fileds', values);
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'account/fetch',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  edit = record => {
    this.setState({
      editVisible: true,
      roleRecord: record,
    });
  };

  handleAdd = fields => {
    this.props.dispatch({
      type: 'role/add',
      payload: {
        ...fields,
      },
      callback: () => {
        message.success('添加成功');
        this.props.dispatch({
          type: 'role/fetch',
        });
        this.props.dispatch({
          type: 'role/fetchName',
        });
      },
    });

    //
    this.setState({
      modalVisible: false,
    });
  };

  downloadFile = () => {
    const fileName = 'export.txt'; // 说白了就是给文件个名字
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {};
      for (const key of Object.keys(fieldsValue)) {
        if (fieldsValue[key]) {
          values[key] = fieldsValue[key];
        }
      }
      //console.log('fileds', values);
      this.setState({
        formValues: values,
      });

      this.props.dispatch({
        // 发送请求
        type: 'account/export',
        payload: values,
        callback: response => {
          const aLink = document.createElement('a'); // 创建a链接
          aLink.style.display = 'none';
          aLink.href = response;
          aLink.download = fileName;
          document.body.appendChild(aLink);
          aLink.click();
          document.body.removeChild(aLink); // 点击完成后记得删除创建的链接
        },
      });
    });
  };
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const { roleType, roleName, userType, userOrg } = this.props.role;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={3} sm={24}>
            <FormItem>{getFieldDecorator('userName')(<Input placeholder="用户名" />)}</FormItem>
          </Col>
          <Col md={3} sm={24}>
            <FormItem >{getFieldDecorator('fullName')(<Input placeholder="姓名" />)}</FormItem>
          </Col>
          <Col md={3} sm={24}>
            {getFieldDecorator('userOrg')(
              <Select allowClear="true" placeholder="单位" style={{ width: '100%' }}>
                {userOrg.map(item => (
                  <Option value={item.code}>{item.name}</Option>
                ))}
              </Select>
            )}
          </Col>
          <Col md={3} sm={24}>
            <FormItem >
              {getFieldDecorator('roleName')(
                <Select allowClear="true" placeholder="角色" style={{ width: '100%' }}>
                  {roleName.map(item => (
                    <Option value={item.code}>{item.name}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={3} sm={24}>
            <FormItem >
              {getFieldDecorator('userType')(
                <Select allowClear="true" placeholder="用户类型" style={{ width: '100%' }}>
                  {userType.map(item => (
                    <Option value={item.code}>{item.name}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button
                style={{ marginLeft: 8 }}
                onClick={() => this.props.history.push(`/usermanage/addaccount/`)}
              >
                添加
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.downloadFile}>
                导出
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    //console.log('account', this.props.account);
    const { account } = this.props;
    const { selectedRows, modalVisible, editVisible } = this.state;

    const columns = [
      {
        title: '用户名',
        dataIndex: 'userName',
      },
      {
        title: '姓名',
        dataIndex: 'fullName',
      },

      {
        title: '角色',
        dataIndex: 'roleName',
      },
      {
        title: '帐号类型',
        dataIndex: 'accountType',
      },
      {
        title: '单位',
        dataIndex: 'userOrg',
      },
      {
        title: '用户类型',
        dataIndex: 'userType',
      },

      {
        title: '手机',
        dataIndex: 'mobPhone',
      },
      {
        title: '状态',
        dataIndex: 'userStatus',
        render(val) {
          return <Badge status={statusMap[val]} text={status[val]} />;
        },
      },
      {
        title: '创建人',
        dataIndex: 'creator',
      },
      {
        title: '创建日期',
        dataIndex: 'createTime',
      },
      {
        title: '最后登录日期',
        dataIndex: 'lastLoginTime',
      },
      {
        title: '操作',
        render: (value, record) => (
          <Fragment>
            <Link
              to={{
                pathname: `/usermanage/editaccount/${record.userName}`,
                record,
              }}
            >
              编辑
            </Link>
            <Divider type="vertical" />
            <a onClick={() => this.disAccount(record)}>
              {record.userStatus === '禁用' ? '启用' : '禁用'}
            </a>
            <Divider type="vertical" />
            <a onClick={() => this.delAccount(record)}>删除</a>
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="用户管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTable
              rowKey="userName"
              selectedRows={selectedRows}
              data={account}
              columns={columns}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
